import { CustomDatabase } from "../utils/db";
import { useIndexStore } from "../store/index";
import { storeToRefs } from "pinia";
import { DataItem } from "../types";
const db = new CustomDatabase();

export default {
  install(app) {
    app.config.globalProperties.$exportCsv = async function (
      record: DataItem,
      tableName: string
    ) {
      const indexStore = useIndexStore();
      const { configData } = storeToRefs(indexStore);
    
      // 解析 configText
      console.log(record.configText); // 打印 configText，确保其内容正确
      const config = JSON.parse(record.configText);
      const {
        eeg_sample_rate,
        eeg_channel_count,
        ir_sample_rate,
        motion
      } = config;
    
      // 从 record 中获取 waveLength，如果不存在则使用默认值 2
      let waveLength = record.waveLength ?? 2; // 如果 waveLength 不存在，默认值为 2
    
      let eegInputMarkerList = JSON.parse(record.eegInputMarkerList) || [];
      let irInputMarkerList = JSON.parse(record.irInputMarkerList) || [];
      let markerList = JSON.parse(record.markerList) || [];
    
      app?.proxy?.loading.show("导出中...");
    
      // 从数据库获取 sourceData
      const res = await db.all(`select * from ${tableName} where recordId = ${record.id}`);
      let sourceData = res.map(item => JSON.parse(item.data)).flat();
    
      if (!Array.isArray(sourceData) || sourceData.length === 0) {
        alert("记录的数据异常！");
        app?.proxy?.loading.hide();
        return;
      }
    
      const metaDataKeys = [
        "ID", "NAME", "DESCRIPTION", "RECORDCREATETIME", "RECORDTOTALTIME", 
        "DEVICE TYPE", "DEVICE SERIAL", "DEVICE FIRMWARE", "EEG CHANNELS", 
        "EEG SAMPLING RATE", "FNIRS CHANNELS", "FNIRS WAVELENGTHS", "FNIRS SAMPLING RATE", 
        "MOTION SAMPLING RATE", "MARKER DESCRIPTION", "LOSS NUM"
      ];

      let csvContent = metaDataKeys.join(",") + "\n";
      csvContent += [
        record.id, // ID
        record.name, // NAME
        record.describe, // DESCRIPTION
        formatUTCTime(record.recoredCreateTime), // RECORDCREATETIME (转换为人类可读时间)
        formatMillisecondsToSeconds(record.recoredTotalTime), // RECORDTOTALTIME (转换为秒并格式化为 XXs)
        "BioMulti Lite", // DEVICE TYPE
        "", // DEVICE SERIAL
        "", // DEVICE FIRMWARE
        eeg_channel_count, // EEG CHANNELS
        eeg_sample_rate, // EEG SAMPLING RATE
        8, // FNIRS CHANNELS (固定值)
        "735nm 850nm", // FNIRS WAVELENGTHS (固定值)
        ir_sample_rate, // FNIRS SAMPLING RATE (使用 ir_sample_rate)
        motion.sample_rate, // MOTION SAMPLING RATE (使用 motion.sample_rate)
        markerList.map(m => `${m.type}:${m.description}`).join(";"), // MARKER DESCRIPTION
        sourceData.filter(ele => ele.isLosspkg).length // LOSS NUM
      ].join(",") + "\n";
    
      const firstPKGData = sourceData[0];
      const firstEntries = Object.entries(firstPKGData);
      const eegChannel = getValueFromEntries(firstEntries, "eeg_channel") || 2;
      const irChannel = getValueFromEntries(firstEntries, "ir_channel") || 8;
      const eegDataNum = getValueFromEntries(firstEntries, "eeg_data_num") || 1;
      // 使用 waveLength
      const thirdRowList = buildThirdRowList(eegChannel, irChannel, waveLength);
      if (thirdRowList.length === 0) {
        alert("不支持的 EEG 通道数！");
        app?.proxy?.loading.hide();
        return;
      }
      csvContent += thirdRowList.join(",") + "\n";
    
      const mergedMarkerData = [...eegInputMarkerList, ...irInputMarkerList].sort((a, b) => a.timestamp - b.timestamp);
      const mergedData = mergeAndSortData(sourceData, mergedMarkerData);
    
      csvContent += convertDataToCSV(mergedData, eegChannel, irChannel, eegDataNum, eeg_sample_rate, waveLength);
    
      downloadCSV(csvContent, tableName, record);
      app?.proxy?.loading.hide();
    }
    
    function getValueFromEntries(entries, key) {
      const entry = entries.find(([k]) => k === key);
      return entry ? entry[1] : undefined;
    }
    
    function buildThirdRowList(eegChannel, irChannel, waveLength) {
      const thirdRowList = ["TIMESTAMP", "EEG.PKN"]; // 修改为 EEG.PKN
    
      // 根据 eegChannel 的值生成 EEG 列名
      if (eegChannel === 2) {
        thirdRowList.push("EEG.FP1", "EEG.FP2");
      } else if (eegChannel === 4) {
        thirdRowList.push("EEG.Fpz", "EEG.AF7", "EEG.AF8", "EEG.M2");
      } else {
        console.error("不支持的 EEG 通道数:", eegChannel);
        return [];
      }
    
      thirdRowList.push("FNIRS.PKN"); // 修改为 FNIRS.PKN
    
      const waveLengthNamePrefixes = ["FNIRS.S1D1", "FNIRS.S1D2", "FNIRS.S1D3", "FNIRS.S1D4", "FNIRS.S2D1", "FNIRS.S2D2", "FNIRS.S2D3", "FNIRS.S2D4"];
      const wavelengths = waveLength === 2 ? ["735", "850"] : ["735", "805", "850"];
    
      waveLengthNamePrefixes.forEach(prefix => {
        wavelengths.forEach(wavelength => {
          thirdRowList.push(`${prefix}.${wavelength}`);
        });
      });
    
      // 增加运动传感器的列名
      thirdRowList.push("ACCEL.X", "ACCEL.Y", "ACCEL.Z", "GYRO.X", "GYRO.Y", "GYRO.Z");
    
      thirdRowList.push("MARKER", "IS_LOSS");
      return thirdRowList;
    }
    
    function mergeAndSortData(sourceData, mergedMarkerData) {
      sourceData.forEach(item => item.source = "sourceData");
      mergedMarkerData.forEach(item => item.source = "mergedMarkerData");
      const mergedData = [...sourceData, ...mergedMarkerData];
      mergedData.sort((a, b) => (a.source === "sourceData" ? a.time_utc : a.time_stamp) - (b.source === "sourceData" ? b.time_utc : b.time_stamp));
      return mergedData;
    }

    function parseChannel(index,length) {
      if(length==2) {
        switch (index) {
          case 0:
            return 1;
          case 1:
            return 0;
          default:
            return 0
        }
      }else if(length == 4) {
        switch (index) {
          case 0:
            return 2;
          case 1:
            return 1;
          case 2:
            return 3;
          case 3:
            return 0;
          default:
            return 0
        }
      }else {
        return 0
      }
    }
    
    function convertDataToCSV(mergedData, eegChannel, irChannel, eegDataNum, eeg_sample_rate, waveLength) {
      let csvContent = "";
      let eegCounter = 0;
      let fnirsCounter = 0;
    
      // 计算总列数
      const totalColumns = 1 + 1 + eegChannel + 1 + irChannel * (waveLength === 2 ? 2 : 3) + 6 + 1 + 1; // TIMESTAMP + EEG.PKN + EEG.FP* + FNIRS.PKN + FNIRS.* + ACCEL.* + GYRO.* + MARKER + IS_LOSS
    
      mergedData.forEach((pkgData, pkgIndex) => {
        if (pkgData.source === "mergedMarkerData") {
          // MARKER 数据行
          const row = new Array(totalColumns).fill(""); // 初始化一行空数据
          row[0] = pkgData.time_stamp; // TIMESTAMP
          row[row.length - 2] = pkgData.type; // MARKER
          csvContent += row.join(",") + "\n";
          return;
        }
    
        const entries = Object.entries(pkgData);
        const pkgType = getValueFromEntries(entries, "pkg_type");
    
        if (pkgType === 1) {
          // EEG 数据行
          const brainElecChannel = getValueFromEntries(entries, "brain_elec_channel");
          if (Array.isArray(brainElecChannel)) {
            for (let col = 0; col < eegDataNum; col++) {
              const timeGap = calculateTimeGap(pkgData, mergedData, pkgIndex, eegDataNum, eeg_sample_rate);
              const row = new Array(totalColumns).fill(""); // 初始化一行空数据
              row[0] = pkgData.time_utc + col * timeGap; // TIMESTAMP
              row[1] = pkgData.pkgnum; // EEG.PKN
              for (let i = 0; i < eegChannel; i++) {
                row[2 + i] = brainElecChannel[parseChannel(i,eegChannel.length)][col]; // EEG.FP*
              }
              // FNIRS 数据列留空
              row[row.length - 1] = pkgData.isLosspkg ? 1 : 0; // IS_LOSS
              csvContent += row.join(",") + "\n";
            }
          }
        } else if (pkgType === 2) {
          // FNIRS 数据行
          const nearInfrared = getValueFromEntries(entries, "near_infrared")?.flat();
          const row = new Array(totalColumns).fill(""); // 初始化一行空数据
          row[0] = pkgData.time_utc; // TIMESTAMP
          row[2 + eegChannel] = pkgData.pkgnum; // FNIRS.PKN
          if (nearInfrared) {
            let irIndex = 0;
            for (let i = 0; i < nearInfrared.length; i++) {
              if (i % (waveLength === 2 ? 2 : 4) !== (waveLength === 2 ? 1 : 3)) {
                row[3 + eegChannel + irIndex] = nearInfrared[i]; // FNIRS.*
                irIndex++;
              }
            }
          }
          row[row.length - 1] = pkgData.isLosspkg ? 1 : 0; // IS_LOSS
          csvContent += row.join(",") + "\n";
        } else if (pkgType === 3) {
          // 运动传感器数据行
          const row = new Array(totalColumns).fill(""); // 初始化一行空数据
          row[0] = pkgData.time_utc; // TIMESTAMP
          row[1] = ""; // EEG.PKN 留空
          for (let i = 0; i < eegChannel; i++) {
            row[2 + i] = ""; // EEG.FP* 留空
          }
          row[2 + eegChannel] = ""; // FNIRS.PKN 留空
          for (let i = 0; i < irChannel * (waveLength === 2 ? 2 : 3); i++) {
            row[3 + eegChannel + i] = ""; // FNIRS.* 留空
          }
          // 填充运动传感器数据
          row[3 + eegChannel + irChannel * (waveLength === 2 ? 2 : 3)] = pkgData.acceleration_x || ""; // ACCEL.X
          row[4 + eegChannel + irChannel * (waveLength === 2 ? 2 : 3)] = pkgData.acceleration_y || ""; // ACCEL.Y
          row[5 + eegChannel + irChannel * (waveLength === 2 ? 2 : 3)] = pkgData.acceleration_z || ""; // ACCEL.Z
          row[6 + eegChannel + irChannel * (waveLength === 2 ? 2 : 3)] = pkgData.gyro_x || ""; // GYRO.X
          row[7 + eegChannel + irChannel * (waveLength === 2 ? 2 : 3)] = pkgData.gyro_y || ""; // GYRO.Y
          row[8 + eegChannel + irChannel * (waveLength === 2 ? 2 : 3)] = pkgData.gyro_z || ""; // GYRO.Z
          row[row.length - 2] = ""; // MARKER 留空
          row[row.length - 1] = pkgData.isLosspkg ? 1 : 0; // IS_LOSS
          csvContent += row.join(",") + "\n";
        }
      });
    
      return csvContent;
    }

    function formatUTCTime(utcTime) {
      return new Date(utcTime).toLocaleString(); // 转换为本地时间
    }
    
    function formatMillisecondsToSeconds(ms) {
      const seconds = Math.floor(ms / 1000); // 转换为秒
      return `${seconds}s`; // 格式化为 XXs
    }

    function calculateTimeGap(pkgData, mergedData, pkgIndex, eegDataNum, eeg_sample_rate) {
      if (pkgData.isLosspkg) {
        let nextIndex = pkgIndex + 1;
        while (nextIndex < mergedData.length && mergedData[nextIndex].pkg_type !== 1) {
          nextIndex++;
        }
        if (nextIndex < mergedData.length && mergedData[nextIndex].pkg_type === 1) {
          return (mergedData[nextIndex].time_mark - pkgData.time_mark) / eegDataNum;
        }
      }
      return 1000 / eeg_sample_rate;
    }
    
    function downloadCSV(csvContent, tableName, record) {
      const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = tableName === "source" ? record.name : `${record.reportName}.csv`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    }
  },
};
